package pres.man.interview.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 两个线程交替输出数字
 *
 * @Author MAN
 * @Date 2021-01-20-16:06
 */
public class Increment {

    private static final Integer MAX_VALUE = 1000;

    private static volatile int INTEGER = 1;

    private static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(2, 2, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1), new ThreadPoolExecutor.AbortPolicy());

    public static void main(String[] args) {
        m1();
    }

    private static void m1() {
        poolExecutor.execute(() -> {
            while (INTEGER <= MAX_VALUE) {
                if (INTEGER % 2 == 1) {
                    System.out.println(Thread.currentThread().getName() + ":" + INTEGER++);
                    try {
                        TimeUnit.SECONDS.sleep(1L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        poolExecutor.execute(() -> {
            while (INTEGER <= MAX_VALUE) {
                if (INTEGER % 2 == 0) {
                    System.out.println(Thread.currentThread().getName() + ":" + INTEGER++);
                    try {
                        TimeUnit.SECONDS.sleep(1L);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
